var $friend = {
    settings : {},
    init : function() {
    },
    add : function($id) {
        var $option = {
            url : 'index.php?c=index&m=addfriend',
            type : 'POST',
            data : 'friend[id]=' + $id + '&friend[token]=' + $('#token').val(),
            dataType : 'text',
            success : function($response) {
                $response = eval('(' + $response + ')')
                if (!$response.result) {
                    return false;
                }

                $('#add_friend_' + $response.id).after(
                    '<span><b>Friend request sent</b></span>');
                $('#add_friend_' + $response.id).remove();
            },
            error : function() {
            }
        };

        $.ajax($option);
    },
    unfriend : function() {
        var $option = {
            url : 'index.php?c=index&m=addfriend',
            type : 'POST',
            data : 'friend[id]=' + $id + '&friend[token]=' + $('#token').val(),
            dataType : 'text',
            success : function($response) {
                $response = eval('(' + $response + ')')
                if (!$response.result) {
                    return false;
                }

                $('#add_friend_' + $response.id).after(
                    '<span><b>Friend request sent</b></span>');
                $('#add_friend_' + $response.id).remove();
            },
            error : function() {
            }
        };

        $.ajax($option);
    },
    accept : function() {
    },
    deny : function() {
    },
    view : function() {
    }
};

var $map = {
    setttings : {},
    init : function() {

    },
    update : function($loca_x, $loca_y) {
        var $option = {
            url : 'index.php?c=index&m=updatelocation',
            type : 'POST',
            data : 'location[loca_x]=' + $loca_x + '&location[loca_y]='
            + $loca_y + '&location[token]=' + $('#token').val(),
            dataType : 'text',
            success : function($response) {
                $response = eval('(' + $response + ')')
                if ($response.result) {
                    $('#err_map').text('')
                    location.reload();
                } else {
                    $('#err_map').text($response.txtErr)
                }
            },
            error : function() {
            }
        };

        $.ajax($option);
    }
};

var $photo = {
    settings : {},
    del : function($id) {
        var $option = {
            url : 'index.php?c=index&m=delphoto',
            type : 'POST',
            data : 'photo[id]=' + $id + '&photo[token]=' + $('#token').val(),
            dataType : 'text',
            success : function($response) {
                $response = eval('(' + $response + ')')
                if ($response.result) {
                    $('#del_' + $response.id).parent().parent().remove();
                } else {
                    alert('Delete unsuccessfully');
                }
            },
            error : function() {
            }
        };

        $.ajax($option);
    },
    like : function($id) {
        var $option = {
            url : 'index.php?c=index&m=likephoto',
            type : 'POST',
            data : 'photo[id]=' + $id + '&photo[token]=' + $('#token').val(),
            dataType : 'text',
            success : function($response) {
                $response = eval('(' + $response + ')')
                if (!$response.result) {
                    return false;
                }

                $('#like_' + $response.id).remove();
                $('#like_text_' + $response.id).html(
                    "Like: " + $response.numLike);
            },
            error : function() {
            }
        };

        $.ajax($option);
    },
    view : function($id) {
        var $option = {
            url : 'index.php?c=index&m=viewphoto',
            type : 'POST',
            data : 'photo[id]=' + $id + '&photo[token]=' + $('#token').val(),
            dataType : 'text',
            success : function($response) {
                $response = eval('(' + $response + ')')
                if (!$response.result) {
                    return false;
                }

                $('#view_' + $response.id).html("View: " + $response.numView);
            },
            error : function() {
            }
        };

        $.ajax($option);
    },
    create : function($id, $name, $container) {
        var $nameShort = $name;
        if($name.length > 5){
            $nameShort = $name.substr(0,5) + '...';
        }
        var $str = "<div class='image'><a href='#' id='view_image_"+$id+"' class='view-image'><img width='100px' height='100px' src='img/thumb/"
        + $id
        + ".jpeg' /><br /></a><span>"
        + $nameShort
        + "</span><span id='full_text_" + $id + "' style='display:none'>"+$name+"</span><br /><span><a class='del-image' id='del_"
        + $id
        + "' href='#'>Delete</a></span><br /><div><span class='view-image' id='view_"
        + $id
        + "'>View: 0</span><br /></div><div><span class='like-image-text' id='like_text_"
        + $id
        + "'>Like: 0</span><br /></div>\
		</div>";
        $('#' + $container).append($str);
    }
}

$(document).ready(
    function() {

        $('.edit').click(function(event) {
            event.preventDefault();
            $id = $(this).attr('id').replace('edit_', '');
            $(this).hide();
            if ($id != 'picture') {
                $('#text_' + $id).hide();
            }
            $('#update_' + $id).show();
            // $('#' + $id).show().val($('#text_' + $id).text());
            $('#' + $id).show();
            $('#cancel_' + $id).show();
        });

        $('.update').click(
            function(event) {
                event.preventDefault();
                $id = $(this).attr('id').replace('update_', '');
                $value = $('#' + $id).val();
                if ($id == 'sex') {
                    $value = 2;
                    if ($('#sex_male').attr('checked')) {
                        $value = 1;
                    }
                }

                if ($id == 'birthday') {
                    if($('#year').val() == -1 ||$('#month').val() == -1 ||$('#day').val() == -1){
                        $value = '-1';
                    }
                    else{
                        $date = [ $('#year').val(), $('#month').val(),
                        $('#day').val() ];
                        $value = $date.join('-');
                    }
                }
                // Check validation....
                $isError = true;
                $isError = $validation.run($id, $value);
                if(!$isError){
                    return false;
                }

                var $option = {
                    url : 'index.php?c=index&m=update',
                    type : 'POST',
                    data : 'profile[name]=' + $id + '&profile[value]='
                    + $value + '&profile[token]='
                    + $('#token').val(),
                    dataType : 'text',
                    success : function($response) {
                        //alert($response);
                        $response = eval('(' + $response + ')');
                        if ($response.result) {
                            $('#text_' + $response.name).text(
                                $response.value);
                            // For sex update...
                            if ($response.name == 'sex') {
                                $('#text_' + $response.name).text(
                                    'Male');
                                if ($response.value == 2) {
                                    $('#text_' + $response.name).text(
                                        'Female');
                                }
                            }

                            $('#update_' + $response.name).hide();// //
                            $('#' + $response.name).hide();// //
                            $('#text_' + $id).show();
                            $('#edit_' + $id).show();
                            $('#er_' + $response.name).text('');
                            $('#cancel_' + $response.name).hide();
                        } else {
                            $('#er_' + $response.name).text($response.txtError);
                        //alert('Update not success');
                        }
                    },
                    error : function() {
                    }
                };

                $.ajax($option);
            });

        //Introduction
        $('.edit-intro').click(function(event) {
            event.preventDefault();
            $(this).hide();
            $('#text_introduction').hide();

            $('#introduction12').show();
            $('.update-intro').show();
        });

        $('#update_introduction').click(
                function(event) {
                    event.preventDefault();
                    var $option = {
                        url : 'index.php?c=index&m=update',
                        type : 'POST',
                        data : 'profile[name]=' + 'introduction' + '&profile[value]='
                        + $('#introduction12').val() + '&profile[token]='
                        + $('#token').val(),
                        dataType : 'text',
                        success : function($response) {
                            //alert($response);
                            $response = eval('(' + $response + ')')
                            if ($response.result) {
                            	$('#text_introduction').text($response.value);
                            	$('#update_introduction').hide();
                                $('#introduction12').hide();

                                $('#edit_introduction').show();
                                $('#text_introduction').show();
                            } else {
                                $('#er_' + $response.name).text($response.txtError);
                            }
                        },
                        error : function() {
                        }
                    };
                    $.ajax($option);
                });

        //Cancel user input
        $('.cancel').click(function(event){
        	event.preventDefault();
        	$id = $(this).attr('id').replace('cancel_', '');
        	$('#edit_' + $id).show();
        	$('#text_' + $id).show();
        	$('#update_' + $id).hide();
        	$('#' + $id).hide();
        	$('#' + $id).val($('#text_' + $id).text());
                $('#er_' + $id).text('');
        	$(this).hide();

        });

        //Cancel picutre upload profile
        $('#cancel_upload_profile').click(function(){
        	$('#picture').hide();
        	$('#edit_picture').show();
        });
        // Add friend...

        // Tab
        $("#tabs").tabs({
            active : 2
        });

        // Upload ajax
        $('#form_upload').ajaxForm(
        {
            success : function($response) {
                $response = eval('(' + $response + ')');
                if ($response.result) {
                    $('#box_upload').dialog('close');
                    $photo.create($response.id, $response.name, 'show_image');
                    $('#err_box_uplad').text('');
                    $('#photo_name, #file_upload').val('');
                }
                else{
                    $('#err_box_uplad').text($response.txtErr);
                }
            },
            complete : function($xhr) {
            }
        });

        // Ajax upload profile...
        $('#profile_form').ajaxForm({
            success : function($response) {
                $response = eval('(' + $response + ')');
                if ($response.result) {
                    $('#profile_user').attr('src', "img/profile/" + $response.src + "?timestamp=" + new Date().getTime());
                    $('#picture').hide();
                    $('#edit_picture').show();
                    $('#er_picture').text('');
                }
                else{
                    $('#er_picture').text($response.txtErr);
                }
            }
        });

        // Picture....
        $("#box_upload").dialog({
            autoOpen : false,
            height : 200,
            width : 300,
            modal : true
        });

        $("#image_show").dialog({
            autoOpen : false,
            height : 600,
            width : 750,
            buttons : {
                Close : function() {
                    $(this).dialog('close');
                }
            }
        });

        // event...
        $('.upload').click(function(event) {
            event.preventDefault();
            $('#box_upload').dialog('open');
        });
        $('#save_coord').click(function(event) {
            event.preventDefault();
            $map.update($('#coord_x').val(), $('#coord_y').val());
        });

        $('.del-image').live("click", function(event) {
            event.preventDefault();
            $confirm = window.confirm('Are you sure to delete');
            if (!$confirm) {
                return false;
            }

            $idPhoto = $(this).attr('id').replace('del_', '');
            $photo.del($idPhoto);

        // $(this).parent().parent().remove();
        })

        $('.like-image').live("click", function(event) {
            event.preventDefault();
            $idPhoto = $(this).attr('id').replace('like_', '');
            $photo.like($idPhoto);

        // $(this).parent().parent().remove();
        })

        // View image...
        $('.view-image').live('click', function(event) {
            event.preventDefault();
            $idPhoto = $(this).attr('id').replace('view_image_', '');
            // Update view + 1
            $photo.view($idPhoto);
            $('#image_album').attr('src', "img/" + $idPhoto + ".jpeg");

            $('#image_show').dialog('open');
            $('#name_picture').html($('#full_text_' + $idPhoto).text());
        });

        // Friend....
        $('.add-friend').click(function(event) {
            event.preventDefault();
            $idFriend = $(this).attr('id').replace('add_friend_', '');
            $friend.add($idFriend);
        });
        //Day processing.
        $day.init();

        //For map..

        var myCenter = new google.maps.LatLng($('#map_x').val(),
            $('#map_y').val());

        function initialize() {

            // apply location marker to centre on
            var mapProp = {
                center : myCenter,
                zoom : 10,
                mapTypeId : google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document
                .getElementById("googleMap"), mapProp);

            var marker = new google.maps.Marker({
                position : myCenter,
                title : 'My centre'
            });

            if ($('#map_empty').val() == 0) {
                var marker = new google.maps.Marker({});
            }

            marker.setMap(map);
            var infowindow = new google.maps.InfoWindow({
                content:"<b>Hi! I'm here?</b><br /><img width='100px' height='100px' src='" + $('#profile_user').attr('src')+ "' />"
            });

            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });


            google.maps.event.trigger(map, 'resize');
            google.maps.event.addListener(map, "click", function(event) {
                var lat = event.latLng.lat();
                var lng = event.latLng.lng();
                $('#coord_x').val(lat);
                $('#coord_y').val(lng)
            });
        }

        google.maps.event.addDomListener(window, 'load', initialize);
    });
